//
//  ChatVideoLeftCell.swift
//  Tinsecret_TW
//
//  Created by wanghui on 2018/12/24.
//  Copyright © 2018年 tst. All rights reserved.
//

import UIKit
import Kingfisher
import SwiftyJSON
import AVFoundation


class ChatVideoLeftCell: ChatBaseCell {
    
    @IBOutlet weak var imgtopConstraint: NSLayoutConstraint!
    @IBOutlet weak var bgtopConstraint: NSLayoutConstraint!
    @IBOutlet weak var avatar: UIImageView!
    @IBOutlet weak var createTimelabel: WHLabel!
    @IBOutlet weak var namelabel: UILabel!
    @IBOutlet weak var pic: UIImageView!
    
    @IBOutlet weak var activityindicator: UIActivityIndicatorView!
    @IBOutlet weak var sendfailureBtn: UIButton!
    @IBOutlet weak var picWidthContraint: NSLayoutConstraint!
    @IBOutlet weak var picHeightContraint: NSLayoutConstraint!
    @IBOutlet weak var videoBtn: UIButton!
    var urlFromSendVC: URL!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        self.videoBtn.layer.cornerRadius = self.videoBtn.frame.width / 2
        self.videoBtn.layer.masksToBounds = true
        self.videoBtn.addTarget(self, action: #selector(playAction), for: .touchUpInside)
        
        self.pic.isUserInteractionEnabled = true
        self.addLongPress()
        
        self.selectionStyle = UITableViewCell.SelectionStyle.none
        self.pic.isUserInteractionEnabled = true
        self.pic.clipsToBounds = true
        self.pic.layer.cornerRadius = 5;
        
        //      let tap = UITapGestureRecognizer(target: self, action: #selector(pictap))
        //      pic?.addGestureRecognizer(tap)
        
        self.avatar.isUserInteractionEnabled = true
        let tapAvatar = UITapGestureRecognizer.init(target: self, action: #selector(tapSelector))
        self.avatar.addGestureRecognizer(tapAvatar)
        
        let tapPic = UITapGestureRecognizer.init(target: self, action: #selector(tapPicture))
        self.pic.addGestureRecognizer(tapPic)
        
        let resend = UITapGestureRecognizer.init(target: self, action: #selector(resendMsg))
        self.sendfailureBtn.addGestureRecognizer(resend)
        
        self.createTimelabel.paddingLeft = 5
        self.createTimelabel.paddingRight = 5
        self.createTimelabel.layer.cornerRadius = 5
        self.createTimelabel.layer.masksToBounds = true
        
        
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
    @objc func tapSelector() {
        print("点击了头像")
    }
    
    @objc func tapPicture() {
        //to
//        delegate?.playVideo(url: model)
    }
    
    @objc func resendMsg() {
        self.model.status = .pending
        self.layoutSubviews()
        self.delegate?.resend(self.model,cell:self)
    }
    
    override func setup(model: ChatMessage) {
        super.setup(model: model)
        if let avatar = model.avatar {
            self.avatar.kf.setImage(with: KF.ImageResource(downloadURL: Common.avatarUrl(avatar) ?? URL(string: "localhost")!), placeholder: #imageLiteral(resourceName: "defaultAvatar"),options: [.processor(CryptorProcessor())])
        } else {
            self.avatar.image = #imageLiteral(resourceName: "timg")
        }
        
        if let thumbnail = model.videoThumbnail {
            self.pic.image = thumbnail
            let size = CGSize(width: model.videoWidth, height: model.videoHeight)
            let result = self.scaleSize(minSize: 70, maxSize: 120, size: size)
            self.picWidthContraint.constant = result.width
            self.picHeightContraint.constant = result.height
            
        }else {
            self.pic.backgroundColor = UIColor.white
            self.videoBtn.setImage(UIImage.init(named: "videoDownload"), for: UIControl.State.normal)
            self.pic.image = UIImage.init(named: "")
            self.picWidthContraint.constant = 65
            self.picHeightContraint.constant = 120
        }

        self.pic.contentMode = .scaleAspectFill
        self.createTimelabel.isHidden = !model.showTimeLabel
        self.createTimelabel.text = model.timeStr
        self.namelabel.text = model.fromName
        self.imgtopConstraint.constant = self.createTimelabel.isHidden == true ? 8: 40
        if model.status == .pending {
            self.activityindicator.isHidden = false
            self.activityindicator.startAnimating()
        } else {
            self.activityindicator.isHidden = true
            self.activityindicator.stopAnimating()
        }
        self.sendfailureBtn.isHidden = !(model.status == .error)
    }
    override func updateUI() {
        super.updateUI()
        DispatchQueue.main.async {
            if self.model.status == .pending {
                self.activityindicator.isHidden = false
                self.activityindicator.startAnimating()
            } else {
                self.activityindicator.isHidden = true
                self.activityindicator.stopAnimating()
            }
            self.sendfailureBtn.isHidden = !(self.model.status == .error)
        }
    }
}

extension ChatVideoLeftCell {
    
    @objc func playAction() {
        //如果已下载, 就开始播放, 如果未下载, 就开始下载
        var videoFileName: String!
        var url: URL!
        if model != nil {
            let json = JSON(parseJSON: model.text ?? "")
            print(" == \(json["fileName"].stringValue)")
            videoFileName = json["fileName"].stringValue
            url = Common.getLocalUrl(videoFileName, file: "videoUrl")
        }else {
            url = self.urlFromSendVC
//            let sendvc = sendToVC()
            
        }
//        let json = JSON(parseJSON: model.text ?? "")
//        print(" == \(json["fileName"].stringValue)")
//        let videoFileName = json["fileName"].stringValue
//        var url = Common.getLocalUrl(videoFileName, file: "videoUrl")
        if  !FileManager.default.fileExists(atPath: url.path) { //开始下载
            let remoteUrl = Common.videourl(videoFileName)!
            FileDownloadTool.instance.download(remoteUrl, to: url, onFinish: {[unowned self] (filePath) in
                DispatchQueue.main.async {
                    url = remoteUrl
                    self.videoBtn.setImage(UIImage.init(named: "videoPlay"), for: UIControl.State.normal)
                    //下载完成后, 设置视频第一帧图片
                    //设置视频第一帧图片
                    let image = VideoUtil.instance.getThumbnailImg(url: url)
                    self.pic.image = image
                    self.model.videoThumbnail = image
                    
                }
            }) { (error) in
                print("\(error)")
            }
        }else {
            delegate?.playVideo(url: url as NSURL)
        }
    }
    
    //长按手势
    @objc func addLongPress() {
        let longPressGes = UILongPressGestureRecognizer.init(target: self, action: #selector(longPressView(_:)))
        //长按等待时间
        longPressGes.minimumPressDuration = 0.5
        
        //长按时候,手指头可以移动的距离
        longPressGes.allowableMovement = 30
        self.pic.addGestureRecognizer(longPressGes)
    }
    
    @objc func longPressView(_ longPressGest:UILongPressGestureRecognizer) {
        if longPressGest.state == UIGestureRecognizer.State.began {
            //长按手势开启
            self.addMenuItem()
        }else {
            
        }
    }
    
    func addMenuItem() {
        self.becomeFirstResponder()
        
        let menuVC = UIMenuController.shared
        //长按手势结束
        menuVC.setTargetRect(CGRect.init(x: (self.pic.frame.origin.x + self.pic.frame.size.width * 0.5), y: self.pic.frame.origin.y, width: 0, height: 0), in: self)
        menuVC.setMenuVisible(true, animated: true)
        print("长按触发")
    }
    
    override var canBecomeFirstResponder: Bool {
        return true
    }
    
//    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
//        
//        //            action == #selector(zhuanfaAction){
//        //            return true
//        //        }else if
//        //         if   action == #selector(delete){
//        //            return true
//        //        }else if action == #selector(reportAction){
//        //            return true
//        //        }
//        
//        if (action == #selector(delete) || action == #selector(reportAction) || action == #selector(zhuanfaAction)){
//            return true
//        }
//        return false
//    }
//    //删除
//    @objc override func delete(_ sender: Any?) {
//        print("删除")
//        //删除
//        self.delegate?.deleteDelegate(msg:model)
//    }
//    //举报
//    @objc func reportAction() {
//        print("举报")
//        //举报
//        self.delegate?.reportDelegate(msg:model)
//    }
//    //转发
//    @objc func zhuanfaAction() {
//        self.delegate?.zhuanfaDelegate(msg: model)
//    }
    
    //move  将video文件从拍摄完毕后存在的文件夹移动到自己指定的 video 文件夹下
    //    videourl:是video一开始所存在的原来的文件夹 相当于temp文件
    func renamedAndSaved(fromVideoUrl: String, videoFileName: String, finish: @escaping (_ success:Bool, _ filePath: String?, _ error: Swift.Error?) -> Void) {
        
        let fm = FileManager.default
        let urlForDocument = fm.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL
        let urlForVideoUrl = urlForDocument.appendingPathComponent("videoThumbnail", isDirectory: true)
        do {
            try FileManager.default.createDirectory(at: urlForVideoUrl, withIntermediateDirectories: true, attributes: nil)
        }catch {
            
        }
        //创建文件地址
       let videoToPath = urlForVideoUrl.appendingPathComponent("\(videoFileName)", isDirectory: false).path
        do {
            //创建文件管理器
            let fileManager = FileManager.default
            print("locationPath--- : \(fromVideoUrl)")
            print("new location --- :\(videoToPath)")
            try fileManager.moveItem(atPath: fromVideoUrl, toPath: videoToPath)
            finish(true, videoToPath, nil)
        }catch {
            finish(false,nil,error)
        }
    }
}

extension ChatVideoLeftCell{
    
    //缩放图片
    func scaleSize(minSize: CGFloat, maxSize: CGFloat, size:CGSize) -> CGSize {
        let origSize = size
        if (origSize.width >= minSize && origSize.height >= minSize) && (origSize.width <= maxSize && origSize.height <= maxSize) {
            return origSize
        }
        let widthHeightRatio = origSize.width/origSize.height  //计算宽高比
        if widthHeightRatio <= (maxSize/minSize) || widthHeightRatio >= (minSize/maxSize) {
            let ratio = max(origSize.width, origSize.height)/maxSize
            return CGSize(width: origSize.width/ratio, height: origSize.height/ratio)
        } else {
            let ratio = max(origSize.width, origSize.height)/minSize
            return CGSize(width: origSize.width/ratio, height: origSize.height/ratio)
        }
    }
}
